package vn.vtsmart.vtcalendarsync;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Name;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class CalendarParser {

	private String mFileName;
	private boolean mStartRead = false;
	private FileInputStream mFis;
	private Workbook mWorkbook;

	public CalendarParser(String _fileName) {
		mFileName = _fileName;
		mWorkbook = openCalendarFile(mFileName);

	}

	public String getmFileName() {
		return mFileName;
	}

	public void setmFileName(String mFileName) {
		this.mFileName = mFileName;
	}

	public void closeCalendarFile() {
		if (mFis != null) {
			try {
				mFis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private Workbook openCalendarFile(String fileName) {

		// Create Workbook instance for xlsx/xls file input stream
		mWorkbook = null;
		try {
			mFis = new FileInputStream(mFileName);

			if (mFileName.toLowerCase().endsWith("xlsx")) {
				mWorkbook = new XSSFWorkbook(mFis);
			} else if (mFileName.toLowerCase().endsWith("xls")) {
				mWorkbook = new HSSFWorkbook(mFis);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mWorkbook;
	}

	public int getSheetNumber() {
		if (mWorkbook == null)
			return 0;
		return mWorkbook.getNumberOfSheets();
	}

	public List<CalendarNameItem> getAllSheetName() {
		List<CalendarNameItem> sheetNameList = new ArrayList<CalendarNameItem>();
		int size = getSheetNumber();
		for (int i = 0; i < size; i++) {
			Sheet sheet = mWorkbook.getSheetAt(i);
			sheetNameList.add(new CalendarNameItem(sheet.getSheetName(), i,
					true));
		}
		return sheetNameList;
	}

	public List<CalendarEvent> parse(int _sheetNumber) {

		String mLocation = null;
		String mMainPerson = null;
		String mAttendtion = null;
		String mPreparePerson = null;
		String mContent = null;
		String mTime = null;
		String mDate = null;
		List<CalendarEvent> eventList = new ArrayList<CalendarEvent>();
		if (mWorkbook == null)
			return eventList;
		// Get the number of sheets in the xlsx/xls file
		int numberOfSheets = mWorkbook.getNumberOfSheets();

		// loop through each of the sheets
		// for (int i = 0; i < numberOfSheets; i++) {
		mStartRead = false;
		// Get the nth sheet from workbook
		Sheet sheet = mWorkbook.getSheetAt(_sheetNumber);

		// every sheet has rows, iterate over them
		Iterator<Row> rowIterator = sheet.iterator();
		while (rowIterator.hasNext()) {

			// Get the row object
			Row row = rowIterator.next();
			// Every row has columns, get the column iterator and
			// iterate over them
			Iterator<Cell> cellIterator = row.cellIterator();

			while (cellIterator.hasNext()) {
				// Get the Cell object
				Cell cell = cellIterator.next();

				// check the cell type and process accordingly
				switch (cell.getCellType()) {
				case Cell.CELL_TYPE_STRING:
					String cellString = cell.getStringCellValue().trim();
					// Check cell is date or not.
					if (!mStartRead && isCellDate(cellString)) {
						mStartRead = true;
					}

					if (mStartRead) {
						switch (cell.getColumnIndex()) {
						case 0:
							mDate = cellString;
							break;
						case 1:
							mTime = cellString;
							break;
						case 2:
							mLocation = cellString;
							break;
						case 3:
							mContent = cellString;
							break;
						case 4:
							mMainPerson = cellString;
							break;
						case 5:
							mPreparePerson = cellString;
							break;
						case 6:
							mAttendtion = cellString;
							break;
						default:
							break;
						}

					}
					break;
				default:
					break;
				}
			}
			if (isCellDate(mDate)
					&& (mDate != null && mLocation != null
							&& mMainPerson != null && mTime != null)) {
				CalendarEvent e = new CalendarEvent(mLocation, mMainPerson,
						mAttendtion, mPreparePerson, mContent, mTime, mDate);
				if (eventList.isEmpty()) {
					eventList.add(e);
				} else {
					CalendarEvent lastestEvent = eventList
							.get(eventList.size() - 1);
					if (compareEvent(lastestEvent, e)) {
						lastestEvent.appendData(e.getmMainPerson(),
								e.getmPreparePerson(), e.getmAttendtion());
					} else {
						eventList.add(e);
					}
				}
			} // End if(mDate != null)

		} // end sheet
			// } // end for

		return eventList;
	}

	public boolean isCellDate(String _cellString) {
		if (_cellString == null)
			return false;
		if (_cellString.toLowerCase().startsWith("thứ 2")
				|| _cellString.toLowerCase().startsWith("thứ 3")
				|| _cellString.toLowerCase().startsWith("thứ 4")
				|| _cellString.toLowerCase().startsWith("thứ 5")
				|| _cellString.toLowerCase().startsWith("thứ 6")
				|| _cellString.toLowerCase().startsWith("thứ 7")
				|| _cellString.toLowerCase().startsWith("chủ nhật"))
			return true;
		return false;

	}

	public boolean compareEvent(CalendarEvent prevEvent, CalendarEvent currEvent) {
		if (prevEvent.getmDate().equals(currEvent.getmDate())
				&& prevEvent.getmTime().equals(currEvent.getmTime())
				&& prevEvent.getmContent().equals(currEvent.getmContent())
				&& prevEvent.getmLocation().equals(currEvent.getmLocation())) {
			return true;
		}
		return false;
	}
}
